<?php

class ProductsController extends AppController {

    public function index($category_id, $page=1) {
        $category = CategoryModel::get($category_id);
        $category->breadcrumbs = CategoryModel::breadcrumbs($category->id);
        $category->children    = CategoryModel::build()
                                    ->where(array('parent_id' => $category_id))
                                    ->query();

        $this->pageTitle = $category->name;
        if (! empty($category->breadcrumbs)) {
            $category->breadcrumbs[0]->children = CategoryModel::build()
                                    ->where(array('parent_id' => $category->breadcrumbs[0]->id))
                                    ->query();

            foreach ($category->breadcrumbs as $cat) {
                $this->pageTitle = "{$cat->name} &raquo; {$this->pageTitle}";
            }
        }

        $categoryChildrenIds = CategoryModel::childrenIds($category_id);

        $products = ProductModel::build()
                ->where(array('category_id' => array_merge(array($category_id), $categoryChildrenIds)))
                ->page($page)
                ->query();
        
        $this->set(compact('products', 'category'));
    }

    public function product($id) {
        $this->pageTitle = $category->name;

        $product  = ProductModel::get($id);
        $category = CategoryModel::get($product->category_id);
        $category->breadcrumbs = CategoryModel::breadcrumbs($category->id);

        $this->pageTitle = $category->name .' &raquo; '. $product->name;

        $this->set(compact('product', 'category'));
    }

}